package com.iagent.spring.resolver;

import com.iagent.annotation.Order;
import com.iagent.bean.IagentFile;
import com.iagent.bean.IagentFile.IagentFileBuilder;
import com.iagent.constant.HttpConstant;
import com.iagent.resovler.parameter.AbstractParameterResolver;
import com.iagent.util.RandomUtils;
import com.iagent.util.StringUtils;
import org.springframework.web.multipart.MultipartFile;

/**
 * @author liujieyu
 * @date 2022/9/20 16:53
 * @desciption
 */
@Order(HttpConstant.MAX_ORDER / 2)
public class MultipartFileParameterResolver extends AbstractParameterResolver {

    @Override
    public Object resolver(Object arg) throws Throwable {
        if (arg instanceof MultipartFile) {
            MultipartFile multipartFile = (MultipartFile) arg;
            String fileName = StringUtils.isEmpty(multipartFile.getOriginalFilename()) ?
                    StringUtils.isEmpty(multipartFile.getName()) ? RandomUtils.getId() : multipartFile.getName()
                    : multipartFile.getOriginalFilename();
            return IagentFile.createBuilder()
                    .name(fileName)
                    .content(multipartFile.getBytes())
                    .build();
        } else if (arg instanceof MultipartFile[]) {
            MultipartFile[] multipartFiles = (MultipartFile[]) arg;
            IagentFileBuilder builder = IagentFile.createBuilder();
            for (MultipartFile multipartFile : multipartFiles) {
                String fileName = StringUtils.isEmpty(multipartFile.getOriginalFilename()) ?
                        StringUtils.isEmpty(multipartFile.getName()) ? RandomUtils.getId() : multipartFile.getName()
                        : multipartFile.getOriginalFilename();
                builder.name(fileName).content(multipartFile.getBytes());
            }
            return builder.build();
        } else {
            return arg;
        }
    }
}
